package cn.icanci.transaction;

import java.sql.*;

/**
 * @Author: icanci
 * @ProjectName: kangaroo-orm
 * @PackageName: cn.icanci.transaction
 * @Date: Created in 2020/8/31 21:14
 * @ClassAction: 测试事务
 */
public class TestTransaction {
    public static void main(String[] args) {
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
            // 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 连接数据库
            conn = DriverManager
                    .getConnection(
                            // 数据库地址
                            "jdbc:mysql://localhost:3306/kangaroo-orm?useSSL=false&serverTimezone=UTC",
                            // 数据库用户名
                            "root",
                            // 数据库密码
                            "root"
                    );
            // 设置为手动提交
            conn.setAutoCommit(false);
            // 编写SQL语句
            String sql = new String("update s_emp set last_name = '啦啦' where id = 3").intern();
            // 创建执行SQL的对象
            int i = 1 / 0;
            statement = conn.createStatement();
            statement.execute(sql);
            // 提交事务
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                // 回滚事务
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } finally {
            if (null != rs) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (null != statement) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (null != conn) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
